<template>
  <div class="device-account-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main class="container">
      <div class="plan-content">
        <div class="plan-title">
          <h3>计划名称</h3>
          <i class="el-icon-plus" @click="handleAdd"></i>
        </div>
        <ul v-if="planList.length">
          <li
            v-for="item in planList"
            :class="[
              item.id === activeId ? 'active' : '',
              item.status === '1' ? 'temporary' : ''
             ]"
            :key="item.id">
            <span @click="handleClick(item)">{{ item.planName }}</span>
            <i v-if="hasTabDelete" class="el-icon-delete" @click="handleDelete(item)"></i>
          </li>
        </ul>
        <div v-else class="empty-content">
          <i class="iconfont iconwushuju"></i>
          <p>暂无数据</p>
        </div>
      </div>
      <div class="table-container">
        <div class="search-container">
          <div class="search-item">
            <div class="content">
              <el-input
                v-model="condition"
                placeholder="根据计划名称筛选"
                @blur="handleSearch"
                suffix-icon="el-icon-search"
                @keydown.native.enter="handleSearch"></el-input>
            </div>
            <div class="label">状态：</div>
            <div class="content">
              <el-select placeholder="请选择审核状态" v-model="status" @change="handleSearch">
                <el-option label="待提交" value="1"></el-option>
                <el-option label="审核中" value="2"></el-option>
                <el-option label="已退回" value="3"></el-option>
                <el-option label="反馈中" value="4"></el-option>
                <el-option label="闭合" value="5"></el-option>
              </el-select>
            </div>
            <el-button class="search-btn" type="primary" @click="handleSearch">
              <i class="el-icon-search"></i>
            </el-button>
            <el-button type="primary" @click="handleRefresh">
              <i class="el-icon-refresh"></i>
            </el-button>
          </div>
          <div class="search-item">
            <el-button v-if="hasTableEdit && hasEdit" type="primary" @click="handleEdit">编辑</el-button>
            <el-button v-if="hasTableCheck && hasCheck" type="primary" @click="handleCheck">审核</el-button>
            <el-button v-if="hasTableSet && hasFeedback" type="primary" @click="handleFeedback">反馈</el-button>
            <el-button v-if="hasTableSet && hasClose" type="primary" @click="handleClose">闭合</el-button>
            <el-button v-if="hasTableDetail && hasView" type="primary" @click="handleView">查看</el-button>
            <el-button v-if="hasTableCheck" type="primary" @click="handleCheckMaterial">审核反馈</el-button>
            <el-button v-if="hasTableSet" type="primary" @click="handleCopyMaterial">抄送记录</el-button>
            <el-button v-if="hasDelete" type="danger" @click="handleDeleteAll">删除</el-button>
          </div>
        </div>
        <el-table
          :data="tableData"
          v-loading="tableLoading"
          element-loading-custom-class="custom-load"
          row-key="id">
          <el-table-column label="" width="60" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.hasCheck" @change="handleChange(scope.row)"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
          <el-table-column label="材料名称" prop="materialName" align="center"></el-table-column>
          <el-table-column label="规格/型号" prop="specs" align="center"></el-table-column>
          <el-table-column label="计划数量" prop="planNum" align="center"></el-table-column>
          <el-table-column label="累计数量" prop="totalNum" align="center"></el-table-column>
          <el-table-column label="单位" prop="unit" align="center"></el-table-column>
<!--          <el-table-column label="关闭状态" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <i v-if="scope.row.closeFlag === '1'" class="iconfont iconyiguanbizhuangtai close-icon"></i>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="状态" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{ statusOptions[scope.row.reviewFlag] || '' }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="是否逾期" prop="overdueDay" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <span-->
<!--                class="day-text"-->
<!--                :style="{ backgroundColor: scope.row.colorStr1 }">-->
<!--                {{ scope.row.overdueDayStr }}-->
<!--              </span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="计划进场时间" prop="planApproachDate" align="center"></el-table-column>
          <div class="empty-content" slot="empty">
            <i class="iconfont iconwushuju"></i>
            <p>暂无数据</p>
          </div>
        </el-table>
        <el-pagination
          v-if="total > 10"
          :page-size="pageSize"
          :current-page="pageNo"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <add-plan
        :visible="visible"
        :type="type"
        :id="planId"
        :status="saveStatus"
        :options="currentData"
        @cancel="visible = false"
        @submit="handleSave">
      </add-plan>
      <view-record
        :visible="recordVisible"
        :id="planId"
        :status="saveStatus"
        :planData="activeData"
        :materialData="materialData"
        @cancel="recordVisible = false">
      </view-record>
      <copy-record
        :visible="copyRecordVisible"
        @cancel="copyRecordVisible = false">
      </copy-record>
      <check-plan
        :visible="checkVisible"
        :type="type"
        @cancel="checkVisible = false"
        @submit="handleSaveCheck">
      </check-plan>
    </main>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import addPlan from '@/components/project/material/addPlan';
import checkPlan from '@/components/project/material/checkPlan';
import viewRecord from '@/components/project/material/viewRecord';
import copyRecord from '@/components/project/material/copyRecord';

export default {
  data() {
    return {
      breadcrumbData: [
        { name: '材料管理' },
        { name: '材料计划' }
      ],
      // 列表数据
      tableData: [],
      tableLoading: false,
      total: 0,
      pageSize: 10,
      pageNo: 1,
      condition: '',
      statusOptions: {
        '0': '未审核',
        '1': '通过',
        '2': '拒绝',
      },
      visible: false,
      type: '',
      planId: '',
      activeId: '',
      hasSearch: false,
      status: '',
      currentData: {},
      materialData: {},
      planList: [],
      recordVisible: false,
      // status 状态：（1：暂存；2：审核中；3：已退回；4：反馈中；5：闭合）
      saveStatus: '',
      activeData: {},
      checkVisible: false,
      copyRecordVisible: false,
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    },
    uuid() {
      return this.userInfo.uuid;
    },
    /**
     * @desc 是否显示编辑按钮
     * @desc status 状态：（1：暂存；2：审核中；3：已退回；4：反馈中；5：闭合）
     */
    hasEdit() {
      const { createUser, status } = this.activeData;
      return createUser === this.uuid && ['1', '3'].includes(status);
    },
    // 是否显示删除按钮
    hasDelete() {
      const { createUser } = this.activeData;
      return createUser === this.uuid;
    },
    // 是否显示审核按钮
    hasCheck() {
      const { reviewUser, status } = this.activeData;
      const hasUser = reviewUser === this.uuid;
      return hasUser && ['2'].includes(status);
    },
    // 是否显示反馈按钮
    hasFeedback() {
      const { createUser, status } = this.activeData;
      return status === '4' && createUser === this.uuid;
    },
    // 是否显示闭合按钮
    hasClose() {
      const { createUser, status } = this.activeData;
      return status === '4' && createUser === this.uuid;
    },
    // 是否显示查看按钮
    hasView() {
      const { status } = this.activeData;
      return ['4', '5'].includes(status);
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.planId = '';
        this.currentData = {};
        this.type = '';
        this.saveStatus = '';
      }
    },
    recordVisible(value) {
      if (!value) {
        this.saveStatus = '';
      }
    },
    activeId(val) {
      if (val) {
        this.getTableData();
      }
    }
  },
  async created() {
    this.getMaterialList(true);
  },
  components: {
    addPlan,
    checkPlan,
    Breadcrumb,
    viewRecord,
    copyRecord,
  },
  methods: {
    // 获取计划列表
    async getMaterialList(hasInit = false) {
      const params = {
        pageFlag: false,
        projectId: this.projectId,
        status: this.status,
        // ...this.setParams(),
      };
      const { success, data: {
        data
      }} = await this.$Model.getMaterialList(params);
      if (success && data) {
        this.planList = data.list || [];
        const activeData = this.planList.find(v => v.id === this.activeId);
        if (activeData) {
          this.getTableData();
          this.activeData = activeData;
        } else {
          this.activeData = this.planList[0] || {};
          this.activeId = this.activeData.id || '';
        }
      }
    },
    /**
     * 获取列表数据
     */
    async getTableData() {
      this.tableLoading = true;
      const params = {
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        projectId: this.projectId,
        planId: this.activeId
      };
      if (this.hasSearch) {
        params.condition = this.condition;
      }
      const { success, data: {
        data
      }} = await this.$Model.getMaterialDetailList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        // const { uuid } = this.userInfo;
        this.tableData = list.map(item => {
          const { overdueDay } = item;
          let colorStr = 'rgba(0, 128, 0, .5)';
          let overdueDayStr = '';
          let dayNum = '';
          try {
            dayNum = Math.abs(overdueDay);
          } catch (e) {}
          if (overdueDay === 0) {
            overdueDayStr = '正常';
          } else if (overdueDay < 0) {
            overdueDayStr = `${dayNum}天后到期`;
            colorStr = 'rgba(255, 255, 0, .5)';
          } else {
            overdueDayStr = `逾期${dayNum}天`;
            colorStr = 'rgba(255, 0, 0, .5)';
          }
          return {
            ...item,
            hasCheck: false,
            overdueDayStr,
            colorStr
          };
        });
        this.total = data.total || 0;
      }
    },
    setParams() {
      const { uuid } = this.userInfo;
      const result = {};
      if (!this.status) return result;
      switch (this.status) {
        case '1':
          result.createUser = uuid;
          result.copyUser = uuid;
          break;
        case '2':
          result.reviewUser = uuid;
          result.copyUser = uuid;
          break;
        case '3':
          result.createUser = uuid;
          break;
        case '4':
          result.createUser = uuid;
          break;
        case '5':
          result.createUser = uuid;
          break;
        default:
          result.createUser = uuid;
          break;
      }
      return result;
    },
    handleSearch() {
      this.planList = [];
      this.clear();
      this.getMaterialList();
    },
    handleRefresh() {
      this.condition = '';
      this.status = '';
      this.planList = [];
      this.clear();
      this.getMaterialList();
    },
    // 切换计划
    handleClick(data) {
      this.activeData = { ...data };
      this.activeId = data.id;
    },
    handleChange(row) {
      const hasCurrent = this.materialData.id === row.id;
      this.materialData = hasCurrent ? {} : { ...row };
      this.tableData = this.tableData.map(item => ({
        ...item,
        hasCheck: hasCurrent ? false : item.id === row.id
      }));
    },
    handleAdd() {
      this.type = 'add';
      this.saveStatus = '';
      this.planId = '';
      this.currentData = {};
      this.visible = true;
    },
    // 编辑
    handleEdit() {
      this.type = 'edit';
      this.planId = this.activeId;
      this.currentData = {
        ... this.activeData,
        materialPlanDetails: this.tableData
      };
      this.visible = true;
    },
    // 审核
    handleCheck() {
      this.type = 'check';
      this.planId = this.activeId;
      this.currentData = {
        ... this.activeData,
        materialPlanDetails: this.tableData
      };
      this.visible = true;
    },
    // 反馈
    handleFeedback() {
      this.saveStatus = '4';
      this.type = 'feedback';
      this.planId = this.activeId;
      this.currentData = {
        ... this.activeData,
        materialPlanDetails: this.tableData
      };
      this.visible = true;
    },
    // 闭合
    handleClose() {
      this.saveStatus = '5';
      this.type = 'close';
      this.planId = this.activeId;
      this.currentData = {
        ... this.activeData,
        materialPlanDetails: this.tableData
      };
      this.visible = true;
    },
    // 查看
    handleView() {
      if (!this.materialData || !this.materialData.id) {
        this.$message.warning('请勾选材料选项');
        return;
      }
      this.recordVisible = true;
    },
    // 审核反馈
    handleCheckMaterial() {
      this.type = 'checkFeedback';
      this.checkVisible = true;
    },
    // 查看抄送记录
    handleCopyMaterial() {
      this.copyRecordVisible = true;
    },
    /**
     * 删除计划
     */
    handleDelete(row) {
      this.$confirm('此操作将删除该计划, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.deleteMaterialPlan({
          ids: row.id
        });
        if (success) {
          this.getMaterialList();
          this.$message.success('删除成功');
        }
      });
    },
    /**
     * 删除计划详情
     */
    handleDeleteAll() {
      if (!this.materialData.id) return;
      this.$confirm('此操作将删除该材料, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delMaterialPlanDetail({
          ids: this.materialData.id
        });
        if (success) {
          this.tableData.length < 2 && this.clear();
          this.getTableData();
          this.$message.success('删除成功');
        }
      });
    },
    // 清除参数
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getTableData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getTableData();
    },
    // 保存
    async handleSave(data) {
      const {
        materialPlanDetails,
        createUserName,
        reviewUserName,
        copyUserName,
        createUser,
        reviewUser,
        copyUser,
        readFlag,
      } = data;
      const params = {
        ...data,
        materialPlanDetails: materialPlanDetails.map(v => ({
          ...v,
          projectId: this.projectId
        }))
      };
      let result = null;
      if (params.status !== '1' && !materialPlanDetails.length) {
        return this.$message.warning('请完善材料信息');
      }
      if (this.type === 'add') {
        result = await this.$Model.addMaterial(params);
      } else if (this.type === 'feedback') { // 反馈
        // 反馈数量有值时附件为空
        const hasEmptyFile = materialPlanDetails.some(item => {
          return (item.currentNum || item.currentNum === 0) && !item.fileUrl;
        });
        if (hasEmptyFile) return this.$message.warning('请上传附件');
        const newParams = materialPlanDetails
          .filter(v => v.currentNum || v.currentNum === 0)
          .map(v => {
            const { currentNum, finishFlag, id, remark, fileUrl } = v;
            return {
              materialId: id,
              readFlag,
              currentNum,
              finishFlag,
              fileUrl,
              remark,
              reviewUser,
              reviewUserName,
              copyUserName,
              copyUser,
              createUser,
              createUserName,
            };
          });
        result = await this.$Model.materialFeedback(newParams);
      } else if (this.type === 'close') {
        const newParams = materialPlanDetails
          .filter(v => v.finishFlag === '1')
          .map(v => {
            const { currentNum, finishFlag, id, remark, fileUrl } = v;
            return {
              materialId: id,
              readFlag,
              currentNum,
              finishFlag,
              fileUrl,
              remark,
              reviewUser,
              reviewUserName,
              copyUserName,
              copyUser,
              createUser,
              createUserName,
            };
          });
        result = await this.$Model.materialFeedback(newParams);
      } else {
        result = await this.$Model.updateMaterial(params);
      }
      if (result && result.success) {
        this.$message.success('保存成功');
        this.getMaterialList();
        this.visible = false;
      }
    },
    // 审核反馈
    async handleSaveCheck(data) {
      const { selection, reason = '', reviewFlag } = data;
      const params = {
        ids: selection.map(v => v.id).join(','),
        reason,
        reviewFlag
      };
      const { success } = await this.$Model.reviewMaterialFeedBack(params);
      if (success) {
        this.$message.success('审核成功');
        this.checkVisible = false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .device-account-page {
    width: 100%;
    height: 100%;
    background-color: $mainBg;
    overflow: hidden;
    main {
      width: 100%;
      height: calc(100% - 50px);
      padding: 20px;
      .plan-content {
        width: 350px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: flex-start;
        float: left;
        .plan-title {
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 10px;
          .el-icon-plus {
            width: 30px;
            height: 30px;
            text-align: center;
            line-height: 30px;
            background-color: rgba(160, 164, 179, 0.4);
            border-radius: 5px;
            cursor: pointer;

            &:hover {
              color: $lightBtnBg;
            }
          }
        }
        .empty-content {
          width: 100%;
          height: calc(100% - 40px);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border: 1px solid $mainColor;
          border-radius: 10px;
          i {
            font-size: 60px;
          }
        }
        ul {
          width: 100%;
          height: calc(100% - 40px);
          overflow-y: auto;
          padding: 20px;
          border: 1px solid $mainColor;
          border-radius: 10px;
          li {
            width: 100%;
            height: 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #fff;
            background-color: $lightBtnBg;
            padding: 0 20px;
            margin-bottom: 15px;
            cursor: pointer;
            border-radius: 5px;
            transition: all .2s;
            &:hover {
              color: $mainColor;
              background-color: $mainBtnBg;
            }
            &.active {
              background-color: $mainBtnBg;
            }
            &.temporary {
              color: #F59A25;
              &:hover {
                color: #F59A25;
              }
            }
            span {
              display: inline-block;
              width: calc(100% - 40px);
              text-align: center;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            i {
              padding: 0 5px;
            }
          }
        }
      }
      .table-container {
        width: calc(100% - 360px);
        height: 100%;
        float: right;
        .search-container {
          width: 100%;
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
          .search-item {
            display: flex;
            align-items: center;
            .el-input {
              width: 300px;
              margin-right: 20px;
            }
          }
          .search-btn {
            margin-left: 20px;
          }
        }
        .el-table {
          width: 100%;
          height: calc(100% - 120px);
        }
        /deep/ .el-table__body-wrapper {
          height: calc(100% - 50px);
          padding-bottom: 46px;
          overflow-y: auto;
          .btn {
            padding: 0 5px;
            cursor: pointer;
            color: $mainColor;
          }
          .close-icon {
            font-size: 30px;
            color: green;
            position: absolute;
            top: calc(50% - 10px);
            left: calc(50% - 15px);
          }
          .day-text {
            display: inline-block;
            padding: 4px 20px;
            border-radius: 4px;
          }
        }
        /deep/ .el-table__header {
          th.is-leaf .el-button span {
            color: #fff;
          }
        }
      }

    }
  }
</style>
